#include "bthread.h"

using namespace bhttp;

std::atomic<int> bthread::num_created_ = 0;

bthread::bthread(const bthread_func& func, const std::string& name)
	: func_(func)
	, name_(name)
{
	num_created_++;
	if (name_.empty())
		name_ = "bthread" + std::to_string(num_created_);
}

bthread::bthread(bthread_func&& func, const std::string& name)
	: func_(std::move(func))
	, name_(name)
{
	num_created_++;
	if (name_.empty())
		name_ = "bthread" + std::to_string(num_created_);
}

bthread::~bthread()
{
	if (started_ && !joined_)
		thd_->detach();
}

void bthread::start()
{
	started_ = true;
	thd_ = std::make_shared<std::thread>(func_);
}

void bthread::join()
{
	joined_ = true;
	thd_->join();
}
